package ejb.contentManagement;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import entities.Room;
import ejb.dto.RoomDTO;

@Stateless
public class RoomBean implements RoomMgr {
	
	@PersistenceContext
    private EntityManager em;
	
	/**
	 * Retrieve entity Room from the associated Id
	 * @param id
	 * @return entity Room associated to the <code>id</code>
	 */
	public Room getRoom(int id) {
		return em.find(Room.class, id);
	}
	
	/**
	 * Retrieve all Room entities
	 * @return all Room entities
	 */
	public List<Room> getAllRooms() {
    	return em.createNamedQuery("Room.findAll", Room.class).getResultList();
    }
	
	/**
	 * Retrieve entity Room from the associated Id and convert it to corresponding RoomDTO
	 */
	@Override
	public RoomDTO getRoomDTO(int id) {
		return  convertToDTO(getRoom(id));
    }
	
	/**
	 * Retrieve all Room entities and convert them into corresponding list of RoomDTO
	 */
	@Override
	public List<RoomDTO> getAllRoomsDTO() {
		List<Room> list = getAllRooms();
		List<RoomDTO> newList = new ArrayList<RoomDTO>();
		for(Room obj : list) {
			newList.add(convertToDTO(obj));
		}
		return newList;
	}
	
	/**
	 * Convert Room entity (parameter <code>r</code>) into corresponding RoomDTO
	 * @param r
	 * @return converted RoomDTO
	 */
	static RoomDTO convertToDTO(Room r) {
		if(r == null){
			return null;
		}
		RoomDTO dto = new RoomDTO();

		dto.setId(r.getId());
		dto.setName(r.getName());
		dto.setBeds(r.getBeds());
		dto.setDescription(r.getDescription());	
		return dto;
	}
	
	/**
	 * Retrieve entity Room from the associated Id and delete the corresponding element from the database
	 */
	@Override
	@RolesAllowed({"ADMINS"})
	public void deleteRoom(int id) {
		em.remove(em.find(Room.class, id));
	}
	
	/**
	 * Create entity Room from corresponding RoomDTO and update corresponding element in database
	 */
	@Override
	@RolesAllowed({"ADMINS"})
	public void updateRoom(RoomDTO updatedRoom) {
		em.merge(new Room(updatedRoom));
	}
	
	/**
	 * Create entity Room from corresponding RoomDTO and insert new element in database
	 */
	@Override
	@RolesAllowed({"ADMINS"})
	public void insertRoom(RoomDTO newRoom) {
		em.persist(new Room(newRoom));
	}
		
	
}
